package com.ad.aidai.fragments.reset_password;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.widgets.edittext.PasswordEditText;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 重置密码
 * <p>
 * Created by rofe on 16/12/18.
 */
public class ResetPasswordFragment extends BaseFragment implements ResetPasswordContract.View {

    @BindView(R.id.password)
    PasswordEditText password;
    private String phone,token;

    /**
     * 重置对话框
     */
    private LoadingDialog loadingDialog;

    private ResetPasswordContract.Presenter mPresenter;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_reset_password, container, false);
    }

    @Override
    protected void initView() {
        //对于刚跳到一个新的界面就要弹出软键盘的情况上述代码可能由于界面为加载完全而无法弹出软键盘。
        //此时应该适当的延迟弹出软键盘如998毫秒（保证界面的数据加载完成）
        password.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                openSoftInput(password);
            }
        }, 500);
    }

    @Override
    protected void initData() {
        new ResetPasswordPresenter(mContext, this).subscribe();
        Bundle bundle = getArguments();
        phone = bundle.getString("phone");
        token = bundle.getString("token");
    }

    @OnClick({R.id.iv_back, R.id.btn_finish, R.id.rl_reset_password_view})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                mPresenter.resetPassword(phone, password.getText().toString(), token);
                break;
            case R.id.iv_back:
                onActivityBackPressed();
                break;
            case R.id.rl_reset_password_view:
                break;
        }
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(mContext);
        loadingDialog.setLoadingText("修改中...")
                .setFailedText("修改失败")
                .setSuccessText("修改成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void resetSuccess() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog != null && loadingDialog.isShowing()) {

                }
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.RESET_PASSWORD_FINISHED));
                        back();
                    }
                });
            }
        }).start();
    }

    private void back(){
        if(password.isFocused()) {
            closeSoftInput(password);
        }
        getFragmentManager().popBackStack();
    }

    @Override
    public void setPresenter(ResetPasswordContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.unSubscribe();
    }

    @Override
    public boolean onActivityBackPressed() {
        back();
        return false;
    }

    /**
     * 关闭软键盘
     *
     * @param view 对应的EditText
     */
    public void closeSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 打开软键盘
     *
     * @param view 对应的EditText
     */
    public void openSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, 0);
    }
}
